#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/7/21  9:35
# @Author: 余浪人
# @email: yulangren520@gmail.com
import re
from apps.control import sys_bp
from flask_login import login_required
from flask import redirect, current_app, jsonify, render_template, request, url_for
from apps.lib.alipay import aliPay, verify_pay_statu, save_order, save_goods
from apps.models.content_model import TL_Content_Model
from apps.lib.public import check_obj, get_uuid16, page_auto
from apps.models.order_model import TL_PayOrder_Model


@sys_bp.route('/pay/<uuid>', endpoint='pay', methods=['GET'])
def pay(uuid):  # 使用异步post  返回支付URL
    content_obj = TL_Content_Model.query.filter_by(status=1, uuid=uuid).first()
    if not content_obj is None and content_obj.permissions:  # 数据获取正确
        alipay = aliPay()
        order_ID = get_uuid16()
        try:
            order = alipay.api_alipay_trade_page_pay(
                subject=f"购买内容: {content_obj.title}",
                out_trade_no=order_ID,  # 订单编号
                total_amount=str(content_obj.reward),  # 订单总金额
                return_url=f'{url_for("sys_bp.verify_pay")}'  # 支付完后，浏览器跳转回的路径
            )
        except AttributeError:
            return jsonify(alipay)
        except TypeError:
            return {'status': 401, 'msg': '密钥配置错误'}
        save_goods([{"sub_uuid": uuid, "order_id": order_ID}])
        return redirect(current_app.config['ALIPAY_URL'] + "?" + order)
    return jsonify({"status": 400, 'msg': '内容获取失败,请勿非法操作'})  # TODO 内容获取失败


# 跳转验证支付
@sys_bp.route('/verify_pay', endpoint='verify_pay', methods=['GET'])
def verify_pay():
    response = verify_pay_statu()
    if response.get('status') == 0:
        save_order(response.get('data'))
        return jsonify({'status': 0, 'msg': '支付成功'})  # 跳转回内容页面
    return jsonify({'status': 1, 'msg': '支付失败'})


# 订单号验证支付宝
@sys_bp.route('/query_order', endpoint='query_order', methods=['POST'])
def query_order():
    '''
    :param order_id: 系统订单编号
    :param trade_no: 支付宝订单编号
    :return:
    '''
    order_id = request.form.get('order_id', '')
    trade_no = request.form.get('trade_no', '')
    if not all([order_id, trade_no]): return jsonify({'status': 1, 'msg': '请输入订单编号'})
    alipay = aliPay()
    try:
        result = alipay.api_alipay_trade_query(out_trade_no=order_id, trade_no=trade_no)
        if result.get("trade_status", "") == "TRADE_SUCCESS" and result.get('code') == '10000':
            save_order(result)
            return jsonify({'status': 0, 'msg': '订单到已有订单!', 'data': result})
        return jsonify({'status': 1, 'msg': '未查询到有效订单!'})
    except AttributeError:
        return alipay


# 订单列表
@sys_bp.route('/order_list', endpoint='order_list', methods=['GET'])
@login_required
def order_list():
    search = request.args.get('search', None)
    if search:
        data_list, page = page_auto(TL_PayOrder_Model.query.filter(TL_PayOrder_Model.out_trade_no == search))
    else:
        data_list, page = page_auto(TL_PayOrder_Model.query.order_by(TL_PayOrder_Model.id.desc()))
    return render_template('system_template/order_list.html', data_list=data_list, page=page)

# 查询订单成功==>> 获取付费内容
